//
//  NewMenuViewController.m
//  eBook
//
//  Created by zhy on 12-12-13.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "NewMenuViewController.h"
#import "AppDelegate.h"
#import "SVProgressHUD.h"
#import "CheckNetwork.h"

@interface NewMenuViewController ()

@end

@implementation NewMenuViewController
@synthesize menuWebView;
@synthesize menuScrollView;

#pragma mark - lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //scrollView
    self.menuScrollView.contentSize = CGSizeMake(1876, 134);
    
    for (int i = 0; i<=10; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(170*i+6, 7, 164, 120)];
        [btn setTag:i];
        [btn addTarget:self action:@selector(chapterSelected:) forControlEvents:UIControlEventTouchUpInside];
        btn.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"menu_%d.png",i]]];
//        [btn setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
        [self.menuScrollView addSubview:btn];
    }
    
    //webView
    menuWebView.scrollView.alwaysBounceVertical = NO;
    menuWebView.scalesPageToFit = NO;
    menuWebView.delegate = self;
//    NSURL *url = [NSURL URLWithString:@"http://jpkc.gdou.com/ebook/01/index.html"];
//    NSURL *url = [NSURL URLWithString:@"http://192.168.4.20/ebook/menu/01.html"];//ftp test
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [menuWebView loadRequest:request];
    
    
    //cover
    
    coverVC = [[CoverViewController alloc] initWithNibName:@"CoverViewController" bundle:nil];
    coverVC.view.frame = CGRectMake(0, 0, 1024, 748);
    coverVC.CoverVCDelegate = self;
    [self.view addSubview:coverVC.view];
    
    [self shouldShowCover];
    
}

- (void)viewDidUnload
{
    [self setMenuScrollView:nil];
    [self setMenuWebView:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft||interfaceOrientation==UIInterfaceOrientationLandscapeRight);
}

//ios 6 rotation
-(NSUInteger)supportedInterfaceOrientations{
//    return UIInterfaceOrientationLandscapeLeft;//xcode 4.4
      return UIInterfaceOrientationMaskLandscape;//xcode 4.5
}

- (BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark - Private Method

-(void) chapterSelected:(id) sender{
    UIButton *btn = (UIButton *)sender;
    int chapter = btn.tag;
    NSLog(@"%d",chapter);
    
    if (chapter == 0) {
        
        [self showCover];
        
    } else {
        //change the outlineURL
        [self changeChapter:chapter];
    }
    
    

}

-(void) shouldShowCover{
    
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Cover"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    
    NSManagedObject *oneObject;
    
    if (objects == nil) {
        NSLog(@"there was a error!");
    }
    
    if ([objects count]>0) {
        oneObject = [objects objectAtIndex:0];
        
        NSNumber *chapter = [oneObject valueForKey:@"chapter"];
        [coverVC.view setHidden:YES];
        [self changeChapter:[chapter intValue]];
    } else{
        [coverVC.view setHidden:NO];
    }
    
}

-(void) saveChaper2CoreData:(int) chapter{
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Cover"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    
    NSManagedObject *oneObject;
    
    if (objects == nil) {
        NSLog(@"there was a error!");
    }
    
    if ([objects count]>0) {
        oneObject = [objects objectAtIndex:0];
    } else {
        oneObject = [NSEntityDescription
                     insertNewObjectForEntityForName:@"Cover"
                     inManagedObjectContext:context];
    }
    NSNumber *c = [NSNumber numberWithInt:chapter];
    [oneObject setValue:c forKey:@"chapter"];
    [appDelegate saveContext];
}

-(void) changeChapter:(int) chapter{
    
    if (CheckNetwork.check) {
        [SVProgressHUD showWithStatus:@"加载数据..."];
        NSString *urlStr = [[NSString alloc] init];
        if (chapter <= 9) {
            urlStr = [NSString stringWithFormat:@"http://jpkc.gdou.com/ebook/menu/0%d.html",chapter];
        } else {
            urlStr = [NSString stringWithFormat:@"http://jpkc.gdou.com/ebook/menu/%d.html",chapter];
        }
        NSLog(@"outline url is %@",urlStr);
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [menuWebView loadRequest:request];
    }    
    [self saveChaper2CoreData:chapter];
}


#pragma mark - webView delegate
//在load url 之前响应，实现监听javascript的event
-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *requestString = [[request URL] absoluteString];
	NSLog(@"string is %@",requestString);
    NSArray *components = [requestString componentsSeparatedByString:@":"];
    
    //    NSLog(@"requestString is %@,count is %d",requestString,[components count]);
    
	if ([components count] > 1 &&
		[(NSString *)[components objectAtIndex:0] isEqualToString:@"ebookapp"]) {
		if([(NSString *)[components objectAtIndex:1] isEqualToString:@"LoadContent"])
		{
            // Call your method in Objective-C method using the above...
            
            
			NSLog([components objectAtIndex:2]);//章节
            NSLog([components objectAtIndex:3]);//主题
            NSLog([components objectAtIndex:4]);//章的总专题数
//            NSLog([components objectAtIndex:4]);//章的总页数
//            NSLog([components objectAtIndex:5]);//跳转的页数，相对专题
            
            Chapter = [[components objectAtIndex:2] intValue];
            Feature = [[components objectAtIndex:3] intValue];
            FeatureCount = [[components objectAtIndex:4] intValue];
//            PageCountofChapter = [[components objectAtIndex:4] intValue];
//            CurrentPageofFeature = [[components objectAtIndex:5] intValue];
            PageCountofChapter = 0;
            CurrentPageofFeature = 1;
            
            NSLog(@" %d  %d %d %d %d",Chapter,Feature,PageCountofChapter,CurrentPageofFeature,FeatureCount);
            
            [self performSegueWithIdentifier:@"MenuToContent" sender:self];
		}
        
        NSLog(@"do not start load");
		return NO;
	}
    NSLog(@"start load!");
	return YES; // Return YES to make sure regular navigation works as expected.
}

-(void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [SVProgressHUD dismissWithError:@"加载失败"];
}

-(void) webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
}

#pragma mark - ContentVCDelegate
-(void) back:(int)chapter{
    //set new chapter and url
    [self changeChapter:chapter];
}

-(void) showCover{
    NSLog(@"show cover");
    [coverVC.view setAlpha:1.0];
    [coverVC.view setHidden:NO];
}

#pragma mark - CoverVC Delegate

-(void) chapterSelect:(int)chapter{
    
    [UIView beginAnimations:@"cover View" context:(void *)coverVC.view];
    [UIView setAnimationDuration:0.5];
    [coverVC.view setAlpha:0.0];
    [UIView commitAnimations];
    
    [self changeChapter:chapter];
}


#pragma mark - Segue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSLog(@"prepareForSegue");
    
    ContentViewController *contentVC = segue.destinationViewController;
    
    contentVC.ContentVCDelegeta = self;
    
    [contentVC setChapter:Chapter andFeature:Feature andPage:CurrentPageofFeature andAllPages:PageCountofChapter andFeatureCount:FeatureCount];
    
}
@end
